package com.scalar.chiptrack.adaptor.ikanos.amkor;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.InventoryLot;
import com.scalar.chiptrack.adaptor.TestLot;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.AssemblyLot;
import com.scalar.chiptrack.adaptor.TestLotBinReport;
import com.scalar.chiptrack.adaptor.utils.ParserResult;
import com.scalar.chiptrack.adaptor.utils.Parser;
import com.scalar.chiptrack.adaptor.utils.ParserFactory;
import com.scalar.chiptrack.adaptor.utils.XLSParserImpl;
import com.scalar.chiptrack.adaptor.dao.ShippedLotDAO;
import com.scalar.chiptrack.adaptor.dao.InventoryLotDAO;
import com.scalar.chiptrack.adaptor.dao.TestAdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.adaptor.dao.AssemblyAdaptorDAO;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.ScalarException;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Date;
import java.io.File;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 1 Oct, 2009
 * Time: 12:16:03 AM
 * To change this template use File | Settings | File Templates.
 */
public class ATPDataParser extends JobHandler implements AdaptorConstants
{
    private HashMap<String, AssemblyLot>  m_assemblyDataMap = new HashMap<String, AssemblyLot>();
    private HashMap<String, InventoryLot> m_dieBankDataMap  = new HashMap<String, InventoryLot>();
    private HashMap<String, TestLot> m_testDataMap          = new HashMap<String, TestLot>();
    private HashMap<String, InventoryLot> m_preTestDataMap	= new HashMap<String, InventoryLot>();
    private HashMap<String, InventoryLot> m_fgDataMap	    = new HashMap<String, InventoryLot>();

    private Logger m_parserLogger       = null;
    private String m_dataOutputDir      = null;

    public  ATPDataParser() throws ScalarException
    {
        try
        {
            m_dataOutputDir = AdaptorUtils.getDataOutputDir( VENDOR_NAME_AMKOR_PH , WIP_TYPE_ASSEMBLY );

            if ( m_dataOutputDir != null )
            {
                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );

                m_parserLogger= AdaptorUtils.getDataParserLogger( m_dataOutputDir,VENDOR_NAME_AMKOR_PH );

                AdaptorUtils.setLogger( m_parserLogger );
                ShippedLotDAO.setLogger( m_parserLogger);
                InventoryLotDAO.setLogger(m_parserLogger);
                TestAdaptorDAO.setLogger( m_parserLogger);
                AssemblyAdaptorDAO.setLogger( m_parserLogger );
            }
        }
        catch ( Exception se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading AMKOR_PH output directory details from database, Exception: " + se );
            System.out.println( "ERROR!! ERROR!! ERROR!! Exception while loading AMKOR_PH output directory details from database, Exception: " + se );
        }
    }
    public static void main( String args[] ) throws Exception
    {
        try
        {
            new ATPDataParser().execute();
        }
        catch ( Exception e )
        {
            throw e;
        }
    }
    public void execute() throws Exception
    {
        AdaptorUtils.printHeader( VENDOR_NAME_AMKOR_PH, CONSTANT_PARSER );

        File doneDestDir = new File( m_dataOutputDir + "/done" );
        File dataoutDir  = new File( m_dataOutputDir );

        File[] fileList = dataoutDir.listFiles();

        if ( ( fileList == null ) || (fileList.length <= 3))
        {
            log("No file found in directory: " + dataoutDir);
            System.out.println("No file found in directory: " + dataoutDir );
            throw new ScalarException("No file found in directory: " + dataoutDir+ "----\n\n" );
        }

        ArrayList<File> successFileList = new ArrayList<File>();

        boolean success = false;

        for ( int i = 0; i < fileList.length; i++ )
        {
            if ( fileList[i].isDirectory() == true )
            {
                continue;
            }

            try
            {
                if ( fileList[i].getName().startsWith( ATPPOP3Adaptor.ATP_WIP_FILE )  || fileList[i].getName().indexOf( ATPPOP3Adaptor.ATP_WIP_FILE )  != -1)
                {
                    //parse ATP WIP wok sheet
                    parseATPWipReport( fileList[i].getAbsolutePath() );

                    ArrayList<TestLotBinReport> testBinList = parseATPFTBinReport( fileList[i].getAbsolutePath(), "Test Yld" );
                    if ( testBinList != null && testBinList.size() > 0 )
                    {
                        //to get the ATP Test Bin Details
                        if ( testBinList.isEmpty() == false )
                        {
                            log( "Updating ATP Binning Information" );
                            TestAdaptorDAO.saveTestBinInfo ( null, testBinList , VENDOR_NAME_AMKOR_PH );
                            success = true;
                        }
                        else
                        {
                            log( "ATP FT Binning Information List is Empty" );
                        }
                    }
                    successFileList.add(fileList[i]);
                }

                success = true;
            }
            catch (Exception e)
            {
                success = false;
                log("Exception while parsing file: " + fileList[i].getAbsolutePath() + "\nException: " + e);
                e.printStackTrace();
                throw e;
            }
        }

        /*Updating the Die Bank Lot Information*/
        try
        {
            // Save Die Bank Information
            if (m_dieBankDataMap.isEmpty() == false)
            {
                log(" Updating Die Bank Lot Information");
                InventoryLotDAO.saveInventoryLot(null, m_dieBankDataMap.values().iterator(), LOCATION_TYPE_DIE_BANK, VENDOR_NAME_AMKOR_PH);
            }
            else
            {
                InventoryLotDAO.closeInventoryLot(null, LOCATION_TYPE_DIE_BANK, VENDOR_NAME_AMKOR_PH);
            }
            success = true;
            m_dieBankDataMap.clear();
            m_dieBankDataMap = null;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log("ERROR!! ERROR!! ERROR!! Could not update Die Bank Lot information into database: " + se);
            throw se;
        }

        /*Updating the Assembly Lot Information*/
        try
        {
            // Step 2
            // Save Assembly Information
            if (m_assemblyDataMap.isEmpty() == false)
            {
                log(" Updating Assembly Lot Information");
                AssemblyAdaptorDAO.saveAssemblyLot(null, m_assemblyDataMap.values().iterator(),WIP_TYPE_ASSEMBLY, VENDOR_NAME_AMKOR_PH);
            }
            else
            {
                AssemblyAdaptorDAO.closeAssemblyLot(null, WIP_TYPE_ASSEMBLY, VENDOR_NAME_AMKOR_PH);
            }

            m_assemblyDataMap.clear();
            m_assemblyDataMap = null;
            success = true;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log("ERROR!! ERROR!! ERROR!! Could not update Assembly Lot information into database: " + se);
            throw se;
        }

        /*try
        {
           if ( m_preTestDataMap.isEmpty() == false )
           {
               log(" Updating Class Stroe Lot Information");
               InventoryLotDAO.saveInventoryLot( null, m_preTestDataMap.values().iterator(), LOCATION_TYPE_PRE_TEST, VENDOR_NAME_AMKOR_PH );
               success = true;
           }
           else
           {
               InventoryLotDAO.closeInventoryLot(null, LOCATION_TYPE_PRE_TEST, VENDOR_NAME_AMKOR_PH  );
           }
      }
      catch (ScalarException se)
      {
          success = false;
          se.printStackTrace();
          log("ERROR!! ERROR!! ERROR!! Could not update Pre Test Lot information into database: " + se);
          throw se;
      }*/
	  /*try
      {
         // Saving FINAL TEST Information
         if ( m_testDataMap.isEmpty() == false )
         {
              log( " Updating Test Lot Information" );
              TestAdaptorDAO.saveTestLot( null,m_testDataMap.values().iterator(), LOCATION_TYPE_FT, VENDOR_NAME_AMKOR_PH );
         }
         else
         {
             TestAdaptorDAO.closeTestLot( null, LOCATION_TYPE_FT, VENDOR_NAME_AMKOR_PH );
         }
         success = true;
      }
      catch ( ScalarException se )
      {
          success = false;
          se.printStackTrace();
          log( "ERROR!! ERROR!! ERROR!! Could not update Test Lot information into database: " + se );
          throw se;
      }*/

        try
       {
           if ( m_fgDataMap.isEmpty() == false )
           {
               log(" Updating Finshed Goods Lot Information");
               InventoryLotDAO.saveInventoryLot( null, m_fgDataMap.values().iterator(), LOCATION_TYPE_FG, VENDOR_NAME_AMKOR_PH );
               success = true;
           }
           else
           {
               InventoryLotDAO.closeInventoryLot(null, LOCATION_TYPE_FG, VENDOR_NAME_AMKOR_PH  );
           }
      }
      catch (ScalarException se)
      {
          success = false;
          se.printStackTrace();
          log("ERROR!! ERROR!! ERROR!! Could not update Finshed Goods Lot information into database: " + se);
          throw se;
      }

        // TO SEND THE NEW LOTS, NEW TRANSIT LOTS, NO PO LOTS, DISCREPANCY LOTS NOTIFICATIONS TO THE USER
        AdaptorDAO.sendAllNotifications( VENDOR_NAME_AMKOR_PH,true, true, true );

        // To Close the Drop Out Lots
        AdaptorDAO.closeDropOutLots( VENDOR_NAME_AMKOR_PH );

        int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( ATPPOP3Adaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR);
        // transaction 9
        try
        {
            if (success)
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, ATPPOP3Adaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
                System.out.println("SUCCESSFULLY UPDATED IN THE DATABASE");
            }
        }
        catch (ScalarException se)
        {
            success = false;  //As filES DATA SAVED , UPDATEING AS SUCCESS
            AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, ATPPOP3Adaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
            log("WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se);
            throw se;
        }

        // Step 10
        // Move the successful files to 'done' directory
        if (success)
        {
            AdaptorUtils.moveFilesToDone( successFileList, doneDestDir);
        }
    }

    private void parseATPWipReport (String fileName ) throws Exception
    {
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );

        ParserResult result            = null;

        InventoryLot inventoryLot  = null;
        AssemblyLot  assemblyLot   = null;
        TestLot      testLot       = null;


        try
        {
            File detailWipFile = new File( fileName );
            if ( !detailWipFile.exists() )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            Parser parser = ParserFactory.getXLSParser( detailWipFile );
            log( "\nFound " + fileName );
            log( "\nParsing the file for ATP Wip Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "\nParsing the file for ATP Wip Report..." );

            ArrayList sheetNamesList = ((XLSParserImpl)parser).getSheetNamesList();

            for(int i= 0; i< sheetNamesList.size(); i++ )
            {
                String partNumber       = null;
                String fabLotNumber     = null;
                String lotNumber        = null;

                String sheetName = (String)sheetNamesList.get( i );
                //System.out.println("sheetName = " + sheetName);
                if ( sheetName != null && ( "Die Bank ATP1".toUpperCase().equalsIgnoreCase(sheetName.toUpperCase())
                        || "ATP1 Die bank".toUpperCase().equalsIgnoreCase(sheetName.toUpperCase()) ) )
                {
                    ((XLSParserImpl)parser).setHeaderRowIdx(0);
                    ((XLSParserImpl)parser).setDataStartRowIdx(1);

                    result = ((XLSParserImpl)parser).parse( sheetName );
                    //System.out.println("result.getHeadings() = " + result.getHeadings());
                    while ( result.next() )
                    {
                        partNumber = result.getString("Source Device(IKAN)");

                        lotNumber  = result.getString("Wafer Run No");

                        if ( partNumber != null && partNumber.trim().length() > 0 && lotNumber != null && lotNumber.trim().length() >0 )
                        {
                             if ( partNumber.endsWith("-00") )
                            {
                                partNumber = partNumber.substring(0, partNumber.lastIndexOf("-00") );
                            }
                            inventoryLot = (InventoryLot)m_dieBankDataMap.get( partNumber + lotNumber );

                            if ( inventoryLot == null )
                            {
                                inventoryLot = new InventoryLot( VENDOR_NAME_AMKOR_PH, LOCATION_TYPE_DIE_BANK );
                                m_dieBankDataMap.put( partNumber + lotNumber, inventoryLot );
                            }

                            int quantity = 0;
                            int wquantity = 0;
                            if (inventoryLot.getQtyIn() != null)
                            {
                                try
                                {
                                    quantity = Integer.parseInt(inventoryLot.getQtyIn());
                                    wquantity = Integer.parseInt(inventoryLot.getWaferQtyIn());
                                }
                                catch (NumberFormatException ignore) {
                                }
                                quantity += result.getInt("Die Unres");
                                wquantity += result.getInt("Wafer Unres");

                            }
                            else
                            {
                                quantity = result.getInt("Die Unres");
                                wquantity = result.getInt("Wafer Unres");
                            }

                            if (quantity > 0 )
                            {
                                inventoryLot.setPartNumber( partNumber );
                                inventoryLot.setLotNumber( lotNumber );
                                inventoryLot.setQtyIn(quantity + "");
                                inventoryLot.setWaferQtyIn( wquantity + "");
                                //inventoryLot.setDateIn( StringUtils.formatDateToString( result.getDate("Plnt Rcpt Date") ) );
                                inventoryLot.setFabLotNumber( lotNumber );
                                inventoryLot.setStatus( LOT_STATUS_RUNNING );
                                inventoryLot.setLotCategory( LOT_CATEGORY_TYPE_PROD );
                            }
                        }
                    }
                }//END OF DIE BANK  ATP 1


                if ( sheetName != null && ("Die Bank ATP3".toUpperCase().equalsIgnoreCase(sheetName.toUpperCase())
                        || "ATP3 Die bank".toUpperCase().equalsIgnoreCase(sheetName.toUpperCase()) ) )
                {
                    ((XLSParserImpl)parser).setHeaderRowIdx(0);
                    ((XLSParserImpl)parser).setDataStartRowIdx(1);

                    result = ((XLSParserImpl)parser).parse( sheetName );

                    while ( result.next() )
                    {
                        partNumber = result.getString("Source Device");

                        lotNumber  = result.getString("Wafer Run No");

                        if ( partNumber != null && partNumber.trim().length() > 0 && lotNumber != null && lotNumber.trim().length() >0 )
                        {
                             if ( partNumber.endsWith("-00") )
                            {
                                partNumber = partNumber.substring(0, partNumber.lastIndexOf("-00") );
                            }
                            inventoryLot = (InventoryLot)m_dieBankDataMap.get( partNumber + lotNumber );

                            if ( inventoryLot == null )
                            {
                                inventoryLot = new InventoryLot( VENDOR_NAME_AMKOR_PH, LOCATION_TYPE_DIE_BANK );
                                m_dieBankDataMap.put( partNumber + lotNumber, inventoryLot );
                            }

                            int quantity = 0;
                            int wquantity = 0;
                            if (inventoryLot.getQtyIn() != null)
                            {
                                try
                                {
                                    quantity = Integer.parseInt(inventoryLot.getQtyIn());
                                    wquantity = Integer.parseInt(inventoryLot.getWaferQtyIn());
                                }
                                catch (NumberFormatException ignore) {
                                }
                                quantity += result.getInt("Die Unres");
                                wquantity += result.getInt("Wafer Unres");

                            }
                            else
                            {
                                quantity = result.getInt("Die Unres");
                                wquantity = result.getInt("Wafer Unres");
                            }

                            if (quantity > 0 )
                            {
                                inventoryLot.setPartNumber( partNumber );
                                inventoryLot.setLotNumber( lotNumber );
                                inventoryLot.setQtyIn(quantity + "");
                                inventoryLot.setWaferQtyIn( wquantity + "");
                                //inventoryLot.setDateIn( StringUtils.formatDateToString( result.getDate("Plnt Rcpt Date") ) );
                                inventoryLot.setFabLotNumber( lotNumber );
                                inventoryLot.setStatus( LOT_STATUS_RUNNING );
                                inventoryLot.setLotCategory( LOT_CATEGORY_TYPE_PROD );
                            }
                        }
                    }
                }//END OF DIE BANK  ATP 3

                //ASSEMBLY
                if ( sheetName != null && "assy".toUpperCase().equalsIgnoreCase(sheetName.toUpperCase()) )
                {
                    ((XLSParserImpl)parser).setHeaderRowIdx(0);
                    ((XLSParserImpl)parser).setDataStartRowIdx(1);

                    result = ((XLSParserImpl)parser).parse( sheetName );
                    					
                    if( result == null )
                    {
                        ((XLSParserImpl)parser).setHeaderRowIdx(1);
                        ((XLSParserImpl)parser).setDataStartRowIdx(2);

                        result = ((XLSParserImpl)parser).parse( sheetName );
                    }

                    while ( result.next() )
                    {
                         partNumber = result.getString("[Target_Device]");
                         fabLotNumber = result.getString("[Wafer_Run_Number]");
                         lotNumber = result.getString("[Customer_Lot_Number]");

                         if ( lotNumber == null)
                         {
                             lotNumber = fabLotNumber;
                         }
                         if ( partNumber != null && partNumber.trim().length() > 0 && lotNumber != null && lotNumber.trim().length() >0 )
                         {
                             assemblyLot = (AssemblyLot)m_assemblyDataMap.get( partNumber + lotNumber + fabLotNumber );

                             if (assemblyLot == null)
                             {
                                 assemblyLot = new AssemblyLot( VENDOR_NAME_AMKOR_PH, WIP_TYPE_ASSEMBLY );
                                 m_assemblyDataMap.put( partNumber + lotNumber + fabLotNumber, assemblyLot);
                             }

                             int quantity =0;

                             if ( assemblyLot.getQtyIn() != null )
                             {
                                try
                                {
                                    quantity = Integer.parseInt(assemblyLot.getQtyIn());
                                }
                                catch (NumberFormatException ignore) {
                                }
                                quantity += result.getInt("[Current_Qty]");
                             }
                             else
                             {
                                 quantity = result.getInt("[Current_Qty]");
                             }
                             if ( assemblyLot.getStage() != null && !result.getString("[Station_Description]").equalsIgnoreCase(assemblyLot.getStage() ) )
                             {
                                 assemblyLot.setStage( assemblyLot.getStage() + "," + result.getString("[Station_Description]"));
                             }
                             else
                             {
                                 assemblyLot.setStage(result.getString("[Station_Description]") );
                             }

                             if ( quantity > 0 )
                             {
                                assemblyLot.setDeviceName(partNumber);
                                assemblyLot.setLotNumber(lotNumber);
                                assemblyLot.setStatus(LOT_STATUS_RUNNING);
                                assemblyLot.setFabLotNumber(fabLotNumber);
                                assemblyLot.setQtyIn( quantity+"");
                                assemblyLot.setCategory( LOT_CATEGORY_TYPE_PROD );
                                if ( result.getDate("[Revised_Shipback_Date]") != null )
                                {
                                    assemblyLot.setExpectedDateOut( StringUtils.formatDateToString(result.getDate("[Revised_Shipback_Date]")) );
                                }
                             }
                         }
                    }
                }//END OF ASSY sheet

                //TEST WIP
                /*if ( sheetName != null && "TEST".equalsIgnoreCase(sheetName ) )
                {
                    ((XLSParserImpl)parser).setHeaderRowIdx(1);
                    ((XLSParserImpl)parser).setDataStartRowIdx(2);

                    result = ((XLSParserImpl)parser).parse( sheetName );

                    while ( result.next() )
                    {
                         partNumber = result.getString("[Target_Device]");
                         fabLotNumber = result.getString("[Customer_Lot_Number]");
                         //lotNumber = result.getString("[Internal_Lot_Number]");

                         if ( lotNumber == null)
                         {
                             lotNumber = fabLotNumber;
                         }
                         if ( fabLotNumber == null )
                         {
                             fabLotNumber = lotNumber;
                         }
                         if ( partNumber != null && partNumber.trim().length() > 0 && lotNumber != null && lotNumber.trim().length() >0 )
                         {

                            testLot = (TestLot) m_atptestDataMap.get( partNumber + lotNumber + fabLotNumber );
                            if (testLot == null)
                            {
                                testLot = new TestLot(VENDOR_NAME_AMKOR_PH, LOCATION_TYPE_FT );
                                m_atptestDataMap.put(partNumber + lotNumber + fabLotNumber, testLot);
                            }

                            int quantity = 0;
                            if (testLot.getQtyIn() != null)
                            {
                                try
                                {
                                    quantity = Integer.parseInt(testLot.getQtyIn());
                                }
                                catch (NumberFormatException ignore) {
                                }
                                quantity += result.getInt("[Current_Qty]");
                            }
                            else
                            {
                               quantity += result.getInt("[Current_Qty]");
                            }

                            if ( quantity > 0 )
                            {
                                testLot.setPartNumber( partNumber );
                                testLot.setLotNumber( lotNumber );
                                testLot.setFabLotNumber( fabLotNumber );
                                if ( result.getDate("FGS in date") != null )
                                {
                                    testLot.setDateIn( StringUtils.formatDateToString(result.getDate("FGS in date") ) );
                                }
                                testLot.setStage( result.getString("[Station_Description]"));
                                testLot.setQtyIn( quantity + "");
                                testLot.setStatus(LOT_STATUS_RUNNING);
                                testLot.setCategory( LOT_CATEGORY_TYPE_PROD );
                            }
                         }
                    }
                }*/

                //FGS
                if ( sheetName != null && "Finished Goods".equalsIgnoreCase(sheetName) )
                {
                    ((XLSParserImpl)parser).setHeaderRowIdx(0);
                    ((XLSParserImpl)parser).setDataStartRowIdx(1);

                    result = ((XLSParserImpl)parser).parse( sheetName );

                    if ( result != null && result.getHeadings() != null && result.getHeadings().size() > 0 )
                    while ( result.next() )
                    {
                        partNumber = result.getString("  [Target_Device]");
                        lotNumber  = result.getString("  [Customer_Lot_Number]");

                        if ( partNumber != null && partNumber.trim().length() > 0 && lotNumber != null && lotNumber.trim().length() >0 )
                        {
                            inventoryLot = (InventoryLot)m_fgDataMap.get( partNumber + lotNumber );

                            if ( inventoryLot == null )
                            {
                                inventoryLot = new InventoryLot( VENDOR_NAME_AMKOR_PH, LOCATION_TYPE_FG );
                                m_fgDataMap.put( partNumber + lotNumber, inventoryLot );
                            }

                            int quantity = 0;
                            if (inventoryLot.getQtyIn() != null)
                            {
                                try
                                {
                                    quantity = Integer.parseInt(inventoryLot.getQtyIn());
                                }
                                catch (NumberFormatException ignore) {
                                }
                                quantity += result.getInt("  [Current_Qty]");
                            }
                            else
                            {
                                quantity += result.getInt("  [Current_Qty]");
                            }

                            if (quantity > 0 )
                            {
                                inventoryLot.setPartNumber( partNumber );
                                inventoryLot.setLotNumber( lotNumber );
                                inventoryLot.setQtyIn(quantity + "");
                                inventoryLot.setFabLotNumber( lotNumber );
                                inventoryLot.setStatus( LOT_STATUS_RUNNING );
                                inventoryLot.setLotCategory( LOT_CATEGORY_TYPE_PROD );
                                inventoryLot.setDateCode( result.getString("  [Lot_Date_Code]") );
                            }
                        }

                    }
                }

            }

        }
        catch(Exception e )
        {
            e.printStackTrace();
            throw e;
        }
    }

    private ArrayList<TestLotBinReport> parseATPFTBinReport( String fileName, String sheetName ) throws Exception
    {
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );
        ParserResult result     = null;

        String lotNumber        = null;
        String partNumber       = null;
        String fablotNumber     = null;
        ArrayList<TestLotBinReport> ftYieldList  = new ArrayList<TestLotBinReport>();

        try
        {
            File detailWipFile = new File( fileName );
            if ( detailWipFile.exists() == false )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            log( "\nFound " + fileName );
            log( "\nParsing the file for Ft Yield Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "\nParsing the file for FT Yield Report..." );

            Parser parser = ParserFactory.getXLSParser( detailWipFile , sheetName );

            ArrayList sheetNamesList = ((XLSParserImpl)parser).getSheetNamesList();

            for(int i= 0; i< sheetNamesList.size(); i++ )
            {
                String sheetListName = (String)sheetNamesList.get( i );
                //System.out.println("sheetName = " + sheetName);
                if ( sheetName != null && sheetListName != null && sheetName.equalsIgnoreCase(sheetListName) )
                {
                    ((XLSParserImpl)parser).setHeaderRowIdx(3);
                    ((XLSParserImpl)parser).setDataStartRowIdx(4);
                    
                    result = ((XLSParserImpl)parser).parse( sheetListName );

                    //System.out.println("result.getString() = " + result.getHeadings() );

                    while ( result.next() )
                    {
                        partNumber   = result.getString("Device Name");
                        fablotNumber = result.getString("Wafer/Metal lots");
                        lotNumber    = result.getString("Lot Number");
                        if ( lotNumber == null)
                        {
                            lotNumber = fablotNumber;
                        }

                        if ( partNumber != null && partNumber.length() > 0 && lotNumber != null && lotNumber.length() > 0 && !lotNumber.startsWith("DAILY REPORT" ) )
                        {
                            TestLotBinReport ftYieldStatus = new TestLotBinReport();

                            ftYieldStatus.setDeviceName( partNumber );
                            ftYieldStatus.setLotNumber( lotNumber );
                            ftYieldStatus.setCustLotNo( fablotNumber );

                            //ftYieldStatus.setPkgType( result.getString("Package") );
                            //ftYieldStatus.setLeadCount( result.getString("L/C") );
                            //ftYieldStatus.setStage( result.getString("INSERTION") ); // Insertion
                            ftYieldStatus.setTestProg(result.getString("Test Program"));
                            ftYieldStatus.setTesterId( result.getString("Tester No") );
                            ftYieldStatus.setDateCode( result.getString("Date Code") );
                            ftYieldStatus.setHandler( result.getString("Handler") );
                            //ftYieldStatus.setLb(result.getString("L/B ID"));
                            ftYieldStatus.setTemp( result.getString("Temp"));
                            //System.out.println(" result.getString(\"Date\") = " +  result.getString("Date"));
                            ftYieldStatus.setDateIn( result.getString("Date") );
                            ftYieldStatus.setDateOut( result.getString("Date") );
                            ftYieldStatus.setInQty( result.getInt("IN    QTY") +"");
                            ftYieldStatus.setPassQty( result.getInt("OUT QTY")+"" );
                            //ftYieldStatus.setDamageQty( result.getString("Defect Qty") );
                            ftYieldStatus.setYield( (result.getDouble("Yield %") * 100)+"".replaceAll("%",""));
                            ftYieldStatus.setBin1( result.getString("Bin1 qty") );
                            ftYieldStatus.setBin2(result.getString("Bin2 qty"));
                            ftYieldStatus.setBin3(result.getString("Bin3 qty"));
                            ftYieldStatus.setBin4(result.getString("Bin4 qty"));
                            ftYieldStatus.setBin5(result.getString("Bin5 qty"));
                            //ftYieldStatus.setBin6(result.getString("Bin 6"));
                            //ftYieldStatus.setBin7(result.getString("Bin 7"));
                            //ftYieldStatus.setBin8(result.getString("Bin 8"));

                            //ftYieldStatus.setLossQty( result.getString("Loss QTY") );
                            //ftYieldStatus.setVmQty( result.getString("VM QTY") );
                            //ftYieldStatus.setOsQty( result.getString("OS QTY") );

                            ftYieldList.add( ftYieldStatus );

                        }
                    }
                }
            }
        }
        catch ( Exception ex )
        {
            System.out.println("ERROR!!!ERROR!!! While Parsing the ATP FT Yield Report");
            ex.printStackTrace();
            throw ex;
        }

        return ftYieldList;
    }
    private void log( String message )
    {
      if ( message == null ) return;

      if ( m_parserLogger != null )
      {
          m_parserLogger.logDebug( message + LINE_SEPARATOR );
      }
      else
      {
          System.out.println( message );
      }
    } // end of log method

}

